package com.prelearning.at_springboot.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.prelearning.at_springboot.entity.Published;
import com.prelearning.at_springboot.entity.Unpublish;
import com.prelearning.at_springboot.mapper.PublishedMapper;
import com.prelearning.at_springboot.service.IPublishedService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.prelearning.at_springboot.utils.WorkWXAPIUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cgr
 * @since 2022-04-10
 */
@Service
public class PublishedServiceImpl extends ServiceImpl<PublishedMapper, Published> implements IPublishedService {

    @Resource
    private PublishedMapper publishedMapper;

    //初始化需要存入数据库的published对象
    @Override
    public Published init(Published published) {
        published.setUseName(WorkWXAPIUtil.getUserInfo(published.getUserId())[0]);
        published.setPublishStatus(1);
        String[] members =WorkWXAPIUtil.getGroupMember(published.getGroupId());
        assert members != null;
        published.setExpectNumber(members.length-1);
        published.setUnsignedNumber(members.length-1);
        published.setResult(WorkWXAPIUtil.getResult(published.getGroupId()).toString());
        return published;
    }

    //根据用户id获取正在发布的签到
    @Override
    public List<Published> getUnfinished(String user_id) {
        return publishedMapper.getByUserId(user_id);
    }

    //根据用户id获取已发布的签到
    @Override
    public List<Published> getFinished(String user_id) {
        return publishedMapper.getFinished(user_id);
    }

    //根据群组id获取已发布签到
    @Override
    public List<Published> getPublished(String owner_id) {
        return publishedMapper.getPublished(owner_id);
    }

    //用户签到和老师标记，修改对应id的签到状态信息 以及签到表单的签到人数信息
    @Override
    public boolean Sign_online(String id, int choice, String studentInfo) {
        Published published = getById(id);
        String result=published.getResult();
        JSONObject object =JSONArray.parseObject(studentInfo);
        JSONArray jsonArray=JSONArray.parseArray(result.substring(10,result.length()-1));

        for(int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            if(Objects.equals(jsonObject.getString("user_id"), object.getString("user_id"))){
                jsonObject.remove("sign_in_status");
                jsonObject.put("sign_in_status",object.getString("sign_in_status"));

                if(Objects.equals(jsonObject.getString("sign_in_time"), "")){
                    jsonObject.remove("sign_in_time");
                    jsonObject.put("sign_in_time",object.getString("sign_in_time"));
                }

//                System.out.println(jsonArray.toString());
                if(Objects.equals(published.getSignInType(), "vote")){
                    String[] voteResult=published.getVoteResult().substring(1,4).split(",");
                    voteResult[choice]=String.valueOf(Integer.parseInt(voteResult[choice])+1);
                    published.setVoteResult("["+voteResult[0]+","+voteResult[1]+"]");
                }
                published.setSignedNumber(published.getSignedNumber()+1);
                published.setUnsignedNumber(published.getUnsignedNumber()-1);
                published.setResult("{\"result\":"+jsonArray.toString()+"}");
                saveOrUpdate(published);

                return true;
            }
        }
        return false;
    }

    //定时刷新数据库调整签到表单的发布状态
    @Override
    public void refresh() {
        List<Published> publishedList= publishedMapper.getPublishing();
        for(Published published :publishedList){
            LocalDateTime endTime=published.getEndTime();
            LocalDateTime nowTime=LocalDateTime.now();
            if(Duration.between( endTime, nowTime).toMillis()>0){
                published.setPublishStatus(2);
                saveOrUpdate(published);
                System.out.println("\n================transfer one in published================");
            }
        }
        System.out.println("\n------------------------cleaned one time in published------------------------");
    }

}
